import React, { useState, useEffect } from 'react';
import PageTitle from '@/components/PageTitle';
import TagTitle from '@/components/TagTitle';
import { Button, Col, Form, Input, message, Row, Select } from 'antd';
import UplodFile from '@/components/FileUpload/UplodFile';
import UplodFiles from '@/components/FileUpload/UplodFiles';
import { connect } from 'umi';
import { insertWorksInfo, queryByCompanyUser, queryByIdWorksInfo, queryByUserNameEntry, queryCentralizationExhibition, queryGroupByCompany } from '@/services/addworks';
// import style from './index.less';
import { CloudUploadOutlined, PlusOutlined } from '@ant-design/icons';
import { REG_EXP_BY_NUMBER } from '@/utils/regular';

const { Option } = Select;

interface areaType {
  name?: string;
  value?: string;
  colon?: boolean;
  required?: boolean;
}

const AddWorks = (props: any) => {
  const [form] = Form.useForm();
  let { dispatch, history, location, isnext = false, userData } = props;
  let { disableds, id, ids } = location?.query ?? {};
  let area: areaType[] = [
    {
      name: '印面释文',
      value: 'printingAnnotations',
      colon: true,
      required: true,
    },
    {
      name: '印顶纽释文',
      value: 'imprintingAnnotations',
      colon: true,
    },
    {
      name: '边款释文',
      value: 'sideStyleAnnotationsA',
      colon: true,
    },
    {
      name: ' ',
      value: 'sideStyleAnnotationsB',
      colon: false,
    },
    {
      name: ' ',
      value: 'sideStyleAnnotationsC',
      colon: false,
    },
  ];
  const [companyList, setCompanyList] = useState<any[]>([]);
  const [nameList, setNameList] = useState<any[]>([]);
  const [taskItem, setTaskItem] = useState<any>({
    exhibitionList: [],
    termsList: [],
    id: undefined,
    item: {},
  });
  const onFinish = (values: any) => {
    if (dispatch) {
      // 判断添加终稿的逻辑
      if (ids) {
        /**
         * 处理所有的图片数据如果有赋值，如果没有则唯空
         */
        let worksPicture = [
          values?.printingSurfaceImg
            ? {
                pictureId: values?.printingSurfaceImg ?? '',
                pictureKey: 'printing',
              }
            : '',
          values?.imprintingImg
            ? {
                pictureId: values?.imprintingImg ?? '',
                pictureKey: 'imprinting',
              }
            : '',
          values?.frameOneImg
            ? {
                pictureId: values?.frameOneImg ?? '',
                pictureKey: 'frameA',
              }
            : '',
          values?.frameTwoImg
            ? {
                pictureId: values?.frameTwoImg ?? '',
                pictureKey: 'frameB',
              }
            : '',
          values?.frameThreeImg
            ? {
                pictureId: values?.frameThreeImg ?? '',
                pictureKey: 'frameC',
              }
            : '',
          ...(values?.imprintingImgs?.length
            ? values?.imprintingImgs.map((el: any, index: number) => ({
                pictureId: el?.value,
                pictureKey: 'other',
              }))
            : []),
        ]?.filter(el => el);

        /**
         * 组合作品上传所需要的数据
         */
        let option = {
          firstDraftWorkId: ids == 'undefined' ? '' : ids,

          worksInfo: {
            ...values,
            id,
          },
          worksPicture,
          worksEnclosures: [],
        };

        insertWorksInfo(option).then(res => {
          if (res?.responseCode == 200) {
            message.success('作品保存成功');
            history.goBack();
          }
        });

        return;
      } else {
        /**
         * 下面三元运算处理了是否是代上传或者作者的操作
         */
        dispatch({
          type: 'addworks/fetch',
          payload: {
            ...values,
            creatorId: isnext ? values?.creatorId * 1 : userData?.id,
            generationId: isnext ? userData?.id : '',
            authorId: values?.creatorId * 1,
          },
        });
        // 判断代上传跳转的路由
        if (isnext) {
          history.push(`${location?.pathname}/two/a?isnext=${isnext ? '1' : ''}`);
          return;
        }
      }
      if (id) {
        history.push(`${location?.pathname}/two?id=${id}&disableds=${disableds ? 1 : ''}`);
      } else {
        history.push(`${location?.pathname}/two?ids=${ids}`);
      }
    }
  };

  useEffect(() => {
    if (!id) {
      form.setFieldsValue(props?.worksData);
      /**
       * 判断是否是代上传如果是请求作者姓名列表
       */
      if (isnext) {
        queryByCompanyUser({ company: props?.worksData?.creatorIdName }).then(res => {
          if (res?.responseCode == 200) {
            setNameList(res?.data);
          }
        });

        queryCentralizationExhibition({ userId: props?.worksData?.authorId }).then(res => {
          if (res?.responseCode == 200) {
            taskItem.exhibitionList = res?.data;
            setTaskItem(() => ({
              ...taskItem,
            }));
          }
        });
        queryByUserNameEntry({ userId: props?.worksData?.authorId }).then(res => {
          if (res?.responseCode == 200) {
            taskItem.termsList = res?.data;
            setTaskItem(() => ({
              ...taskItem,
            }));
          }
        });
      }
    } else {
      /**
       * 编辑操作回显选择的数据
       */
      queryByIdWorksInfo({ id }).then(res => {
        if (res?.responseCode == 200) {
          let data = res?.data;
          form.setFieldsValue({
            ...data?.worksInfo,
            printingSurfaceImg: getId(data?.worksPicture, 'printing'),
            imprintingImg: getId(data?.worksPicture, 'imprinting'),
            frameOneImg: getId(data?.worksPicture, 'frameA'),
            frameTwoImg: getId(data?.worksPicture, 'frameB'),
            frameThreeImg: getId(data?.worksPicture, 'frameC'),
            worksEnclosures: data?.worksEnclosures.map((el: any, index: number) => ({
              key: index + 1,
              value: el.fileId,
            })),
          });
        }
      });
    }

    /**
     * 判断是否是代上传如果是请求单位信息
     */
    if (isnext) {
      queryGroupByCompany({}).then(res => {
        if (res?.responseCode == 200) {
          setCompanyList(res?.data);
        }
      });
    }
  }, []);

  /**
   * 获取图片组合数据
   * @param data
   * @param key
   */
  const getId = (data: any, key: string) => {
    return data?.find((el: any) => el.pictureKey == key)?.pictureId ?? '';
  };

  /**
   * 选择所属单位
   * @param e
   */
  const onChange = (e: string) => {
    form.resetFields(['creatorId']);
    queryByCompanyUser({ company: e }).then(res => {
      if (res?.responseCode == 200) {
        setNameList(res?.data);
      }
    });
  };

  const render = (
    <div style={{ color: '#cbcbcb' }}>
      <CloudUploadOutlined style={{ fontSize: 100 }} />
      <div>
        <p>请上传印面图片</p>
        <p>支持jpg、png格式</p>
        <p>上传后图片请将图片裁剪为1:1比例的方图</p>
        <p>请对作品充分留白</p>
      </div>
    </div>
  );

  const renderList = (
    <div style={{ color: '#cbcbcb' }}>
      <PlusOutlined style={{ fontSize: 100 }} />
      <div>
        <p>请上传印面图片</p>
        <p>支持jpg、png格式</p>
        <p>可添加3张边款图片，图片比例不限</p>
      </div>
    </div>
  );

  /**
   *选择作者姓名获取词条展览
   * @param value
   */
  const getTask = (value: string) => {
    form.setFieldsValue({
      exhibitionId: undefined,
      entryId: undefined,
    });
    queryCentralizationExhibition({ userId: value }).then(res => {
      if (res?.responseCode == 200) {
        taskItem.exhibitionList = res?.data;
        setTaskItem(() => ({
          ...taskItem,
        }));
      }
    });
    queryByUserNameEntry({ userId: value }).then(res => {
      if (res?.responseCode == 200) {
        taskItem.termsList = res?.data;
        setTaskItem(() => ({
          ...taskItem,
        }));
      }
    });
  };

  let prop = {
    render: renderList,
    disabled: disableds,
  };

  return (
    <div className="works_table">
      <Form labelCol={{ span: 6 }} wrapperCol={{ span: 20 }} layout="horizontal" onFinish={onFinish} form={form}>
        <PageTitle title={isnext ? '印稿代传' : '印作品上传'} />
        {isnext ? (
          <div className="works_form">
            <TagTitle title={'作者信息'} />

            <div className="works_form_row">
              <Row>
                <Col span={6}>
                  <Form.Item label="所属单位" name="creatorIdName" rules={[{ required: true, message: '请选择作者单位' }]}>
                    <Select size="large" onChange={onChange} placeholder="请选择作者单位" style={{ width: 200 }} allowClear>
                      {companyList?.map((el, index) => (
                        <Option key={index + '123123_id_key'} value={el}>
                          {el}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="作者姓名" name="creatorId" rules={[{ required: true, message: '请选择作者姓名' }]}>
                    <Select size="large" placeholder="请选择作者姓名" onChange={getTask} style={{ width: 200 }} allowClear>
                      {nameList?.map((el, index) => (
                        <Option key={index + '123123_id_key'} value={el.id}>
                          {el?.userName}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="展览名称" name="exhibitionId" rules={[{ required: true, message: '请选择展览名称' }]}>
                    <Select size="large" style={{ width: 200 }} placeholder="请选择展览名称" allowClear>
                      {taskItem?.exhibitionList?.map((el, index) => (
                        <Option key={index + '123123_id_key'} value={el.id}>
                          {el?.exhibitionName}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col span={6}>
                  <Form.Item label="选择词条" name="entryId" required={false}>
                    <Select size="large" style={{ width: 200 }} placeholder="请选择词条名称" allowClear>
                      {taskItem?.termsList?.map((el, index) => (
                        <Option key={index + '123123_id_key'} value={el.id}>
                          {el?.entryName}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </div>
          </div>
        ) : null}
        <TagTitle title={disableds ? '查看印作品内容' : '编辑印作品内容'} />

        <div className="works_form">
          <Form.Item className="printingSurfaceImg" label="印面图片" name="printingSurfaceImg" rules={[{ required: true, message: '请上传印面信息' }]}>
            <UplodFile render={render} disabled={disableds} />
          </Form.Item>
          <div className="hr"></div>
          <Form.Item className="printingSurfaceImg" label="印顶/纽图片" name="imprintingImg">
            <UplodFile render={render} disabled={disableds} />
          </Form.Item>
          <div className="hr"></div>
          <div className="work_form_upload_list">
            <p>边款图片：</p>
            <Form.Item label="" name="frameOneImg">
              <UplodFile {...prop} />
            </Form.Item>
            <Form.Item name="frameTwoImg">
              <UplodFile {...prop} />
            </Form.Item>
            <Form.Item name="frameThreeImg">
              <UplodFile {...prop} />
            </Form.Item>
          </div>
          <div className="hr"></div>
          {ids ? null : (
            <>
              {area.map(el => (
                <Form.Item
                  colon={el.colon}
                  key={el.value + '1231321_123123'}
                  label={el.name}
                  name={el.value}
                  className="printing"
                  rules={[{ required: el.required, message: `${el.name}不能为空` }]}>
                  <Input.TextArea allowClear disabled={disableds} placeholder="多行输入" />
                </Form.Item>
              ))}
              <div className="hr"></div>
              <Form.Item label="作者姓名" name="authorsName" rules={[{ required: true, message: '作者姓名不能为空' }]}>
                <Input disabled={disableds} style={{ width: 180 }} placeholder="请输入作者姓名" allowClear />
              </Form.Item>

              {/* new add */}
              <Form.Item
                label="作者年龄"
                name="authorAge"
                rules={[
                  {
                    pattern: REG_EXP_BY_NUMBER,
                    message: '只能输入纯数字',
                  },
                ]}>
                <Input disabled={disableds} style={{ width: 180 }} placeholder="请输入作者年龄" allowClear />
              </Form.Item>

              <Form.Item
                label="作者性别"
                name="authorSex"
                rules={[
                  {
                    pattern: REG_EXP_BY_NUMBER,
                    message: '只能输入纯数字',
                  },
                ]}>
                <Select disabled={disableds} size="large" onChange={onChange} placeholder="请选择作者性别" style={{ width: 180 }} allowClear>
                  <Option value={0}>男</Option>
                  <Option value={1}>女</Option>
                </Select>
              </Form.Item>

              <Form.Item label="作者职业" name="authorWork">
                <Input disabled={disableds} style={{ width: 180 }} placeholder="请输入作者职业" allowClear />
              </Form.Item>
              {/* new add  end*/}

              <Form.Item className="printing" label="个人简介" name="personalProfile">
                <Input.TextArea autoSize={{ minRows: 5, maxRows: 6 }} placeholder="请输入个人简介。。。" allowClear disabled={disableds} />
              </Form.Item>
              <Form.Item className="printing" label="所属单位" name="company">
                <Input disabled={disableds} placeholder="请输入所属单位" allowClear />
              </Form.Item>
              <div className="hr"></div>

              <TagTitle title={'附件'} />
              <div className="export_list">
                <div className="span_info">请尽量使用Word格式的文件，并保持文件大小在10MB以内</div>
                <Form.Item label="" name="worksEnclosures">
                  <UplodFiles
                    render={
                      <div style={{ color: '#cbcbcb' }}>
                        <PlusOutlined style={{ fontSize: 30 }} />
                        <div>上传文件</div>
                      </div>
                    }
                    disabled={disableds}
                    type={true}
                  />
                </Form.Item>
              </div>
              <div className="hr"></div>
            </>
          )}
        </div>

        <div className="add">
          <Button
            className="btn_cold"
            onClick={() => {
              history.go(-1);
            }}>
            取消
          </Button>
          <Button className="btn_red" htmlType="submit">
            {ids ? '保存' : '下一步'}
          </Button>
        </div>
      </Form>
    </div>
  );
};

interface connectState {
  addworks: any;
  login: any;
}
export default connect(({ login, addworks }: connectState) => ({
  userData: login?.userData,
  worksData: addworks.worksData,
}))(AddWorks);
